/*
 * PatternValidator.java
 * 
 * Created on 22-Aug-2007, 18:57:07
 * 
 * Copyright (C)
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA 02111-1307 USA
 */

package com.grubby.databean.constraints.validation;

import com.grubby.databean.constraints.annotation.Pattern;
import java.lang.annotation.Annotation;
import java.util.regex.Matcher;

/**
 * A validator for the {@link Pattern Pattern} constraint.
 * @see Pattern
 * 
 * <p>
 * Note this has been adapted from an Annotation processing example created by 
 * Anders Holmgren of Sun Microsystems
 * </p>
 *
 * @author Anders Holmgren, with alterations by A. HARMEL-LAW. 
 * E: andrew.harmel.law@gmail.com
 * @version 0.1
 */
public class PatternValidator extends AbstractConstraintValidator {
    
    /**
     * Constructs a PatternValidator object.
     */
    @SuppressWarnings("unchecked")
    public PatternValidator() {
        super(Pattern.class);
    }

    public ConstraintViolation validate(Object objValue, Annotation constraint) {
        ensureConstraintIsSupported(constraint);

        Pattern p = (Pattern)constraint;
        ConstraintViolation result = null;

        if (objValue == null) {
            result = new ConstraintViolation(p,
                "Pattern constraint violated. The String provided is null");
        }
        
        String value = (objValue != null ? objValue.toString() : null);
        if (value != null && !matches(value, p.value())) {
            result = new ConstraintViolation(p,
                "Pattern constraint violated. The String " + value + 
                " does not conform to the pattern " + p.value());
        }

        return result;
    }
    
    private boolean matches(String value, String pattern) {
        /*
         * TODO: Determine whether compiling patterns each time is expensive
         * and if so consider caching.
         */
        // Need fully qualified class name to avoid name clash
        java.util.regex.Pattern p = java.util.regex.Pattern.compile(pattern);
        Matcher m = p.matcher(value);
        return m.matches();
    }
}
